﻿using System;
using Microsoft.Win32;

namespace DenisVuyka.Controls.PropertyGrid.Metadata
{
  [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
  public class OpenFileDialogOptionsAttribute : Attribute
  {
    public string Filter { get; protected set; }
    public bool AddExtension { get; set; }
    public bool CheckFileExists { get; set; }
    public bool CheckPathExists { get; set; }
    public string DefaultExt { get; set; }
    public bool DereferenceLinks { get; set; }
    public int FilterIndex { get; set; }
    public bool Multiselect { get; set; }
    public bool ReadOnlyChecked { get; set; }
    public string Title { get; set; }
    public bool ShowReadOnly { get; set; }
    public bool ValidateNames { get; set; }

    public OpenFileDialogOptionsAttribute(string filter)
    {
      if (string.IsNullOrEmpty(filter)) throw new ArgumentNullException("filter");
      ReadConfiguration(null);      
      this.Filter = filter;      
    }

    public bool HasTitle
    {
      get { return !string.IsNullOrEmpty(Title); }
    }

    public bool HasDefaultExt
    {
      get { return !string.IsNullOrEmpty(DefaultExt); }
    }

    public virtual void ReadConfiguration(OpenFileDialog dialog)
    {
      if (dialog == null) dialog = new OpenFileDialog();
      this.AddExtension = dialog.AddExtension;
      this.CheckFileExists = dialog.CheckFileExists;
      this.CheckPathExists = dialog.CheckPathExists;
      this.DefaultExt = dialog.DefaultExt;
      this.DereferenceLinks = dialog.DereferenceLinks;
      this.Filter = dialog.Filter;
      this.FilterIndex = dialog.FilterIndex;
      this.Multiselect = dialog.Multiselect;
      this.ReadOnlyChecked = dialog.ReadOnlyChecked;
      this.ShowReadOnly = dialog.ShowReadOnly;
      this.Title = dialog.Title;
      this.ValidateNames = dialog.ValidateNames;
    }

    public virtual void ConfigureDialog(OpenFileDialog dialog)
    {
      if (dialog == null) dialog = new OpenFileDialog();

      dialog.Filter = this.Filter;
      dialog.AddExtension = this.AddExtension;
      dialog.CheckFileExists = this.CheckFileExists;
      dialog.CheckPathExists = this.CheckPathExists;
      if (this.HasDefaultExt) dialog.DefaultExt = this.DefaultExt;
      dialog.DereferenceLinks = this.DereferenceLinks;
      dialog.FilterIndex = this.FilterIndex;
      dialog.Multiselect = this.Multiselect;
      dialog.ReadOnlyChecked = this.ReadOnlyChecked;
      dialog.ShowReadOnly = this.ShowReadOnly;
      if (this.HasTitle) dialog.Title = Title;
      dialog.ValidateNames = this.ValidateNames;
    }
  }
}
